package me.pplay.playtalk.database;

import java.util.ArrayList;
import java.util.List;

import me.pplay.playtalk.bean.NotificationEntity;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.util.LogManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class NotificationDb {
	private final String NOTIFICATION_TABLE	= "notification";
	private DbHelper dbHelper;
	public NotificationDb(){}
	
	public NotificationDb(Context context){
		dbHelper	= new DbHelper(context);
	}
	
	/**
	 * 添加
	 * @return
	 */
	public boolean add(NotificationEntity entity){
		dbHelper.openDatabase();
		boolean bool = false;
		long result = 0;
		try{
			ContentValues values = new ContentValues();
			values.put("_id", entity.get_id());
			values.put("myskyid", Globals.skyid);
			values.put("type", entity.getType());
			values.put("content", entity.getContent());
			values.put("time", entity.getTime());
			result = dbHelper.db.insert(NOTIFICATION_TABLE, null, values);
		}catch (Exception e) {
			LogManager.LogShow("NotificationDb", e.getMessage());
		}finally{
			dbHelper.closeDatabase();
			if(result >0)
				bool = true;
		}
		return bool;
	}
	
	
	/**
	 * @param type 0:纯文本
	 * @return
	 */
	public List<NotificationEntity> queryList(int type){
		dbHelper.openDatabase();
		List<NotificationEntity> notiList		= new ArrayList<NotificationEntity>();
		Cursor cursor 			= null;
		try {
			String sql			= "select * from " + NOTIFICATION_TABLE + " where myskyid = "+ Globals.skyid + " and type=" + type +" order by time desc";
			cursor 				= dbHelper.db.rawQuery(sql, null);
			if(cursor != null){
				while (cursor.moveToNext()) {
					NotificationEntity noti	= new NotificationEntity();
					noti.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
					noti.setType(cursor.getInt(cursor.getColumnIndex("type")));
					noti.setContent(cursor.getString(cursor.getColumnIndex("content")));
					noti.setTime(cursor.getString(cursor.getColumnIndex("time")));
					notiList.add(noti);
	            }
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			dbHelper.closeDatabase();
		}
		return notiList;
	}
	
	/**
	 * 删除
	 */
	public void delete(int _id) {
		dbHelper.openDatabase();
		dbHelper.db.delete(NOTIFICATION_TABLE, "_id=" + _id + "", null);
		dbHelper.closeDatabase();
	}
}
